﻿using System;
using System.Collections.Generic;

namespace KeyWordSearch.TreeParser
{
	[System.Diagnostics.DebuggerStepThrough]
	internal class AstNode
	{
		private List<AstNode> Childes_;

		private AstNode Parent_;


		public AstNode(Token value,AstNode parent)
		{
			Parent_ = parent;
			Value = value;
			Childes_ = new List<AstNode>();
		}

		public AstNode(Token value)
			:this(value,null)
		{
		}


		public AstNode Parent
		{
			get
			{
				return Parent_;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("Parent");
				}
				else
				{
					Parent_ = value;
				}
			}
		}

		public Token Value
		{
			get;
			set;
		}

		public void AddChilde(AstNode childe)
		{
			if (childe == null)
			{
				throw new ArgumentNullException("childes");
			}
			else
			{
				childe.Parent = this;
				Childes_.Add(childe);
			}
		}

		public void DeleteChild(AstNode childe)
		{
			if (childe == null)
			{
				throw new ArgumentNullException("childes");
			}
			else if (childe.Parent != this)
			{
				throw new InvalidOperationException();
			}
			else
			{
				Childes_.Remove(childe);
			}
		}

		public AstNode this[int index]
		{
			get
			{
				return Childes_[index];
			}
		}

		public int Count
		{
			get
			{
				return Childes_.Count;
			}
		}

		public override string ToString()
		{
			return Value == null ? "NULL" : Value.TextValue;
		}
	}

}
